package com.shushan.collect;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.exam.ExamFragment;
import com.shushan.exam.adapter.ExamFragmentAdapter;
import com.shushan.exam.bean.ExerciseBean;
import com.shushan.mixedexam.BaseExamFragment;
import com.shushan.mixedexam.bean.MutiExerciseBean;
import com.shushan.mixedexam.englishwords.EnglishWordsExam3Fragment;
import com.shushan.mixedexam.englishwords.EnglishWordsExamFragment;
import com.shushan.mixedexam.hearing.HearingExamFragment;
import com.shushan.mixedexam.speaking.SpeakingExamFragment;
import com.shushan.mixedexam.strangewords.StrangeWordsExam2Fragment;
import com.shushan.mixedexam.strangewords.StrangeWordsExamFragment;
import com.shushan.mixedexam.sync.FillBlankExamFragment;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetListCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.util.DownloadUtil;
import com.shushan.util.ToolUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: CollectDetailActivity
 * @Desciption: 收藏夹详情
 * @author: yichaohua
 * @date: 2018-02-06
 */
public class CollectDetailActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    private static final String TAG = "CollectDetailActivity";

    private ViewPager viewPager;
    private ExamFragmentAdapter examFragmentAdapter;
    private ImageView examButton;
    private TextView tvSubjectName, tvCurrentNum, tvTopicTotalNum;
    private Button btnNextTopic;

    private int pageIndex = 0;
    private int subjectId;
    private int exercisesType;
    private int num;
    private int maxPage = 0;
    private int page = 1;
    private final static int PAGE_SIZE = 20;
    private final static int FRESH_SIZE = 5;
    private List<Fragment> fragments = new ArrayList<Fragment>();

    Handler scrollHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    viewPager.setCurrentItem(msg.arg1, true);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.collect_detail_activity);

        ScreenManager sm = new ScreenManager();
        if(!sm.setDeepStatusBar(true,this)){
            findViewById(R.id.titlebar_divider).setVisibility(View.GONE);
        }

        num = getIntent().getIntExtra("num", 0);
        subjectId = getIntent().getIntExtra("subjectId", 0);
        exercisesType = getIntent().getIntExtra("exercisesType", 0);

        maxPage = ((num % PAGE_SIZE) == 0) ? (num / PAGE_SIZE) : ((num / PAGE_SIZE) + 1);
        Log.i(TAG, "num=" + num + " maxPage=" + maxPage);

        initView();

        getCollects();
    }

    private void initView() {
        tvSubjectName = findViewById(R.id.tv_subject_name);
        tvCurrentNum = findViewById(R.id.tv_current_num);
        tvTopicTotalNum = findViewById(R.id.tv_topic_total_num);
        tvTopicTotalNum.setText("/" + num + ")");
        btnNextTopic = findViewById(R.id.btn_next_topic);
        examButton = findViewById(R.id.collect_detail_title_img);
        examButton.setOnClickListener(this);
        viewPager = findViewById(R.id.collect_detail_vp);
        viewPager.addOnPageChangeListener(this);

        tvSubjectName.setText(ToolUtils.getSubjectNameFromId(subjectId));
        tvCurrentNum.setText("(" + 1);
        btnNextTopic.setOnClickListener(this);

        examFragmentAdapter = new ExamFragmentAdapter(this, getSupportFragmentManager(), fragments);
        viewPager.setAdapter(examFragmentAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.collect_detail_title_img:
                if(examFragmentAdapter.getCount() == 0){
                    return;
                }
                MutiExerciseBean exerciseBean = ToolUtils.getMutiExerciseBean(examFragmentAdapter.getItem(pageIndex));
                if (exerciseBean.child_collect == 1) {
                    doPostCollect(2);
                } else {
                    doPostCollect(1);
                }
                break;
            case R.id.btn_next_topic:
                Message message = scrollHandler.obtainMessage(0);
                message.arg1 = pageIndex + 1;
                scrollHandler.sendMessageDelayed(message, 100);
                tvCurrentNum.setText("(" + (pageIndex + 1));
                break;
            default:
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        pageIndex = position;

        tvCurrentNum.setText("(" + (position + 1));
        showCollect();

        if ((page <= maxPage) && ((position + 1) % PAGE_SIZE) == (PAGE_SIZE - FRESH_SIZE)) {

            getCollects();
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    public void getCollects() {
        int childId = BabyApplication.getInstance().getCurrentChildId();

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.COLLECT_DETAIL_NEW);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", childId)
                .putValue("subject_id", subjectId + "")
                .putValue("exercises_type", exercisesType + "")
                .putValue("page", page)
                .putValue("pagesize",PAGE_SIZE);

        if (page == 1) {
            showWaitDialog();
        }

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetListCommListener<MutiExerciseBean>() {
                    @Override
                    protected void onCommon() {
                        if (page == 1) {
                            dismissWaitDialog();
                        }
                    }

                    @Override
                    protected void onSuccess(List<MutiExerciseBean> exerciseBeanList) {
                        setData(exerciseBeanList);

                        page++;
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void setData(List<MutiExerciseBean> exerciseBeanList) {
        if (ToolUtils.isListEmpty(exerciseBeanList)) {
            return;
        }

        downloadAllExamAudio(exerciseBeanList);

        fragments.addAll(getExamFragments(true, 0, exerciseBeanList));

        examFragmentAdapter.notifyDataSetChanged();

        if (page == 1) {
            showCollect();
        }

    }

    private List<Fragment> getExamFragments(boolean isOnlyDisplay, int beginIndex, List<MutiExerciseBean> exerciseBeans) {
        int startIndex = 0;
        List<Fragment> fragments = new ArrayList<>();
        if (!ToolUtils.isListEmpty(exerciseBeans)) {
            for (int i = 0; i < exerciseBeans.size(); i++) {
                MutiExerciseBean exerciseBean = exerciseBeans.get(i);
                switch (Integer.parseInt(exerciseBean.exercises_type)) {
                    case Constants.TYPE_SYNC_EXERCISE://同步练习
                        if (exerciseBean.exercises_level.equals("0")) {//单选题
                            com.shushan.mixedexam.sync.ExamFragment syncFragment = com.shushan.mixedexam.sync.ExamFragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                            syncFragment.setOnAnswerSelectListener(null);
                            fragments.add(syncFragment);
                        } else if (exerciseBean.exercises_level.equals("1")) {//填空题
                            FillBlankExamFragment blankFragment = FillBlankExamFragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                            blankFragment.setOnAnswerSelectListener(null);
                            fragments.add(blankFragment);
                        }
                        startIndex++;
                        break;
                    case Constants.TYPE_STRANGE_WORDS_EXERCISE://生字练习
                        if (exerciseBean.exercises_level.equals("1")) {//生字题型2
                            StrangeWordsExam2Fragment exam2Fragment = StrangeWordsExam2Fragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, DownloadUtil.getStrangeWordsExamAudioPath(exerciseBean), exerciseBean);
                            exam2Fragment.setOnAnswerSelectListener(null);
                            fragments.add(exam2Fragment);
                        } else if (exerciseBean.exercises_level.equals("0")) {//生字题型1
                            StrangeWordsExamFragment examFragment = StrangeWordsExamFragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                            examFragment.setOnAnswerSelectListener(null);
                            fragments.add(examFragment);
                        }
                        startIndex++;
                        break;
                    case Constants.TYPE_SPEAKING_EXERCISE://口语练习
                        SpeakingExamFragment examFragment = SpeakingExamFragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                        examFragment.setOnAnswerSelectListener(null);
                        fragments.add(examFragment);
                        startIndex++;
                        break;
                    case Constants.TYPE_ENGLISH_WORDS_EXERCISE://单词练习
                        switch (Integer.parseInt(exerciseBean.exercises_level)) {
                            case 0://题型1
                            case 1://题型2
                            case 3://题型4
                                EnglishWordsExamFragment fragment124 = EnglishWordsExamFragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                                fragment124.setOnAnswerSelectListener(null);
                                fragments.add(fragment124);
                                break;
                            case 2://题型3
                                EnglishWordsExam3Fragment fragment3 = EnglishWordsExam3Fragment.newInstance(this, isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                                fragment3.setOnAnswerSelectListener(null);
                                fragments.add(fragment3);
                                break;
                        }
                        startIndex++;
                        break;
                    case Constants.TYPE_HEARING_EXERCISE://听力练习
                        HearingExamFragment hearingFragment = HearingExamFragment.newInstance(isOnlyDisplay, beginIndex + startIndex + i, exerciseBean);
                        hearingFragment.setOnAnswerSelectListener(null);
                        fragments.add(hearingFragment);
                        startIndex++;
                        break;
                }
            }
        }
        return fragments;
    }

    private void downloadAllExamAudio(List<MutiExerciseBean> mutiExerciseBeans) {
        List<String[]> downloadInfos = new ArrayList<>();
        for (int i = 0; i < mutiExerciseBeans.size(); i++) {
            MutiExerciseBean exerciseBean = mutiExerciseBeans.get(i);
            switch (Integer.parseInt(exerciseBean.exercises_type)) {
                case Constants.TYPE_STRANGE_WORDS_EXERCISE://生字练习
                    if (exerciseBean.exercises_level.equals("1")) {//生字练习题型2
                        String[] strings = {DownloadUtil.getStrangeWordsExamAudioPath(exerciseBean), BuildConfig.wxUpImgBaseUrl + exerciseBean.voice};
                        downloadInfos.add(strings);
                    }
                    break;
                case Constants.TYPE_SPEAKING_EXERCISE://口语练习
                    String[] strs = {DownloadUtil.getSpeakingExamAudioPath(exerciseBean.outline_detail_id, exerciseBean.id), BuildConfig.wxUpImgBaseUrl + exerciseBean.voice};
                    downloadInfos.add(strs);
                    break;
                case Constants.TYPE_ENGLISH_WORDS_EXERCISE://单词练习
                    if (!exerciseBean.exercises_level.equals("1")) {//除了题型2都有音频需要下载
                        String[] strs2 = {DownloadUtil.getEnglishWordsStudyAudioPath(exerciseBean.outline_detail_id, exerciseBean.id), BuildConfig.wxUpImgBaseUrl + exerciseBean.voice};
                        downloadInfos.add(strs2);
                    }
                    break;
                case Constants.TYPE_HEARING_EXERCISE://听力练习
                    String[] strs3 = {DownloadUtil.getHearingExamAudioPath(exerciseBean.outline_detail_id, exerciseBean.id), BuildConfig.wxUpImgBaseUrl + exerciseBean.voice};
                    downloadInfos.add(strs3);
                    break;
            }
        }
        DownloadUtil.getInstance().createAllTypeExamDownloadDir();
        DownloadUtil.getInstance().downloadData(this, downloadInfos);
    }

    private void showCollect() {
        if(examFragmentAdapter.getCount() == 0){
            return;
        }
        MutiExerciseBean exerciseBean = ToolUtils.getMutiExerciseBean(examFragmentAdapter.getItem(pageIndex));

        if (exerciseBean.child_collect == 1) {
            examButton.setBackgroundResource(R.drawable.exam_title_collected);
        } else {
            examButton.setBackgroundResource(R.drawable.exam_title_uncollect);
        }
    }

    private void dealCollect() {
        if(examFragmentAdapter.getCount() == 0){
            return;
        }
        MutiExerciseBean exerciseBean = ToolUtils.getMutiExerciseBean(examFragmentAdapter.getItem(pageIndex));
        if (exerciseBean.child_collect == 1) {
            examButton.setBackgroundResource(R.drawable.exam_title_uncollect);
            exerciseBean.child_collect = 0;
        } else {
            examButton.setBackgroundResource(R.drawable.exam_title_collected);
            exerciseBean.child_collect = 1;
        }

    }

    /**
     * 收藏和取消收藏
     *
     * @param collectType 1:收藏试题2:取消收藏试题
     */
    private void doPostCollect(final int collectType) {
        if(examFragmentAdapter.getCount() == 0){
            return;
        }
        MutiExerciseBean exerciseBean = ToolUtils.getMutiExerciseBean(examFragmentAdapter.getItem(pageIndex));
        int childId = BabyApplication.getInstance().getCurrentChildId();

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.TOPIC_COLLECT);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", childId)
                .putValue("exercise_id", exerciseBean.id)
                .putValue("subject_id", exerciseBean.subject_id)
                .putValue("exercises_type", exercisesType)
                .putValue("type", collectType + "");

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        dealCollect();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    protected void onTitleBack() {
        onBackAction(100);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackAction(100);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
